package com.crazymaker.springcloud.base.security.token;

import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.Collections;

/**
 * jwt token
 */
public class JwtAuthenticationToken extends AbstractAuthenticationToken {

    /**
     * 封装的jwt信息
     */
    private transient DecodedJWT decodedJWT;

    /**
     * 用户信息
     */
    private UserDetails userDetails;

    public JwtAuthenticationToken(DecodedJWT decodedJWT) {
        super(Collections.emptyList());
        this.decodedJWT = decodedJWT;
    }

    public JwtAuthenticationToken(Collection<? extends GrantedAuthority> authorities, DecodedJWT decodedJWT
        , UserDetails userDetails) {
        super(authorities);
        this.decodedJWT = decodedJWT;
        this.userDetails = userDetails;
    }


    @Override
    public Object getCredentials() {
        return userDetails;
    }

    @Override
    public Object getPrincipal() {
        if (decodedJWT == null) {
            return userDetails;
        }
        return decodedJWT.getSubject();
    }

    public DecodedJWT getDecodedJWT() {
        return decodedJWT;
    }

    @Override
    public void setDetails(Object userDetails) {
        this.setAuthenticated(true);
        super.setDetails(userDetails);
    }
}
